package com.faxsun.core.service.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.faxsun.core.persist.dao.BannerDao;
import com.faxsun.core.persist.entity.BannerPO;
import com.faxsun.core.service.BannerService;

import mtons.modules.pojos.Page;

@Transactional
public class BannerServiceImpl implements BannerService {

	private static final String CACHE="bannerCache";
	private static final Logger log=LoggerFactory.getLogger(BannerServiceImpl.class);
	
	@Autowired
	BannerDao bannerDao;

	@Override
	public void addBanner(BannerPO banner) {
		validate(banner);
		banner.setCreateTime(new Date());
		bannerDao.save(banner);

	}

	private void validate(BannerPO banner) {
		if (StringUtils.isEmpty(banner.getAlt())) {
			banner.setAlt(banner.getUrl());
		}
		if (banner.isDisplayed() && banner.getDisplayOrder() < 1) {
			banner.setDisplayOrder(1);
		}
	}

	@Override
	public void updateBannr(BannerPO banner) {
		validate(banner);
		BannerPO dbBanner=bannerDao.get(banner.getId());
		dbBanner.setUpdateTime(new Date());
		dbBanner.setDisplayed(banner.isDisplayed());
		dbBanner.setDisplayOrder(banner.getDisplayOrder());
		dbBanner.setTargetUrl(banner.getTargetUrl());
		dbBanner.setAlt(banner.getAlt());
		dbBanner.setUrl(banner.getUrl());
		bannerDao.update(dbBanner);
	}

	@Override
	public List<BannerPO> listBanners() {
		return bannerDao.list();
	}

	@Override
	public List<BannerPO> listDisplayedBanners() {
		return bannerDao.listDisplayedBanners();
	}

	@Override
	public Page listByPage(Page page) {
		List<BannerPO> ret = bannerDao.pageBanners(page);
		page.setResults(ret);
		return page;
	}

	@Override
	public BannerPO findById(long id) {
		return bannerDao.get(id);
	}

}
